package com.duoduo.demo.springnoxml;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class DatabaseConfig {

	@Value("${jdbc.driver}")
	private String jdbcDriver;
	@Value("${jdbc.username}")
	private String jdbcUsername;
	@Value(value = "${jdbc.password}")
	private String jdbcPassword;
	@Value(value = "${jdbc.url}")
	private String jdbcUrl;

	private static DriverManagerDataSource dataSource = null;

	@Bean
	public DataSource dataSource() {
		if (dataSource == null) {
			dataSource = new DriverManagerDataSource();
			dataSource.setDriverClassName(jdbcDriver);
			dataSource.setUsername(jdbcUsername);
			dataSource.setPassword(jdbcPassword);
			dataSource.setUrl(jdbcUrl);
		}
		return dataSource;
	}

	@Bean
	public JdbcTemplate jdbcTemplate() {
		JdbcTemplate jdbcTemplate = new JdbcTemplate();
		jdbcTemplate.setDataSource(dataSource());
		return jdbcTemplate;
	}

	@Bean
	public DataSourceTransactionManager transactionManager() {
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
		transactionManager.setDataSource(dataSource());
		return transactionManager;
	}
}
